package com.hzvdvmc.autosale.setting.ui;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;

import com.hzvdvmc.autosale.R;
import com.hzvdvmc.autosale.base.ActionbarActivity;
import com.hzvdvmc.autosale.constant.ResultEnum;
import com.hzvdvmc.autosale.constant.SpKey;
import com.hzvdvmc.autosale.seriaport.SeriaCmdRequestManager;
import com.hzvdvmc.autosale.seriaport.SerialCallback;
import com.hzvdvmc.autosale.seriaport.SerialClientManager;
import com.hzvdvmc.autosale.seriaport.SerialCmdEnum;
import com.hzvdvmc.autosale.setting.adapter.SimpleTextSpinnerAdatper;
import com.hzvdvmc.autosale.setting.adapter.TestReusltRvAdapter;
import com.hzvdvmc.autosale.setting.bean.TestResultBean;
import com.hzvdvmc.autosale.setting.bean.TuneSetBean;
import com.hzvdvmc.autosale.util.GsonUtils;
import com.hzvdvmc.autosale.util.LogUtil;
import com.hzvdvmc.autosale.util.SPUtils;
import com.hzvdvmc.autosale.util.StringUtil;
import com.hzvdvmc.autosale.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.hzvdvmc.autosale.constant.TimeConstant.OUTRESULT_WAIT;
import static com.hzvdvmc.autosale.constant.TimeConstant.OUTRESULT_WAIT_INTERVAL;

/**
 * 电机测试
 */
public class MachineTestActivity extends ActionbarActivity {

    private static final String TAG = "serial";

    @BindView(R.id.spinner_shoper_no)
    Spinner spinnerShoperNo;
    @BindView(R.id.spinner_row)
    Spinner spinnerRow;
    @BindView(R.id.spinner_column)
    Spinner spinnerColumn;
    @BindView(R.id.btn_test)
    Button btnTest;
    @BindView(R.id.rv_result)
    RecyclerView rvResult;
    private SerialClientManager serialClientManager;
    private CountDownTimer countDownTimer;
    private boolean isContinueExe = true;//是否继续执行
    private Timer timer = new Timer();

    @OnClick(R.id.btn_test)
    public void testBtn() {
        resultList.clear();
        resultList.addAll(getTestTuneNOList());
        mRvRestultAdapter.notifyDataSetChanged();

        testOut(0);

    }

    private List<String> shoperList = new ArrayList<>();
    private List<String> rowList = new ArrayList<>();
    private List<String> columnList = new ArrayList<>();

    SpinnerAdapter adapter1;
    SpinnerAdapter adapter2;
    SpinnerAdapter adapter3;

    private int defalutCount = 20;

    private String tuneSetJson;
    private TuneSetBean mDataBean;
    private String[] cabinetNameArray = {
            "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N",
            "O", "P", "Q", "R", "S", "T",
            "U", "V", "W", "X", "Y", "Z"};

    private RecyclerView.Adapter mRvRestultAdapter;
    private List<TestResultBean> resultList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_machine_test);
        ButterKnife.bind(this);
        setCustomeActiorBar("电机测试");

        initRecyclerView();

        initData();
        initSpinner();
    }

    private void initRecyclerView() {
        mRvRestultAdapter = new TestReusltRvAdapter(resultList);
        rvResult.setLayoutManager(new LinearLayoutManager(this));
        rvResult.setAdapter(mRvRestultAdapter);
    }

    private void initData() {
        tuneSetJson = SPUtils.getInstance().getString(SpKey.TUNE_SET_JSON);
        LogUtil.i("上次保存的货道数据：" + tuneSetJson);
        if (!TextUtils.isEmpty(tuneSetJson)) {
            mDataBean = GsonUtils.GsonToBean(tuneSetJson, TuneSetBean.class);

        }
        if (mDataBean != null) {
            initSpinnerList(mDataBean.getDataList().size());
        } else {
            initSpinnerList(defalutCount);
        }
    }

    private void initSpinnerList(int count) {
        for (int i = 1; i <= count; i++) {
            if (i < 10) {
                shoperList.add("0" + i);
            } else {
                shoperList.add("" + i);
            }
        }
    }


    private void initSpinnerRow(int size) {
        rowList.clear();
        for (int i = 1; i <= size; i++) {
            if (i < 10) {
                rowList.add("0" + i);
            } else {
                rowList.add("" + i);
            }
        }
        adapter2 = new SimpleTextSpinnerAdatper(rowList);
        spinnerRow.setAdapter(adapter2);
    }

    private void initSpinnerColumn(int size) {
        columnList.clear();
        columnList.add("所有");
        for (int i = 1; i <= size; i++) {
            if (i < 10) {
                columnList.add("0" + i);
            } else {
                columnList.add("" + i);
            }
        }
        adapter3 = new SimpleTextSpinnerAdatper(columnList);
        spinnerColumn.setAdapter(adapter3);
    }

    private void initSpinner() {
        adapter1 = new SimpleTextSpinnerAdatper(shoperList);
        adapter2 = new SimpleTextSpinnerAdatper(rowList);
        adapter3 = new SimpleTextSpinnerAdatper(columnList);

        spinnerShoperNo.setAdapter(adapter1);
        spinnerShoperNo.setPrompt("请选择柜号");

        spinnerRow.setAdapter(adapter2);
        spinnerRow.setPrompt("请选择货盘");

        spinnerColumn.setAdapter(adapter3);
        spinnerColumn.setPrompt("请选择货道");

        spinnerShoperNo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (mDataBean != null) {
                    rowList.clear();
                    //初始化货盘数
                    int size = mDataBean.getDataList().get(position).getDataList().size();
                    initSpinnerRow(size);
                } else {
                    initSpinnerRow(defalutCount);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spinnerRow.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (mDataBean != null) {
                    columnList.clear();

                    String column = mDataBean.getDataList()
                            .get(getCabietPosition())
                            .getDataList().get(position)
                            .getTuneCount();

                    initSpinnerColumn(Integer.parseInt(column));
                } else {
                    initSpinnerColumn(defalutCount);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    public int getCabietPosition() {
        return spinnerShoperNo.getSelectedItemPosition();
    }

    public int getRowPosition() {
        return spinnerRow.getSelectedItemPosition();
    }

    public int getColumnPosition() {
        return spinnerColumn.getSelectedItemPosition();
    }

    public String getCabitNO() {
        return cabinetNameArray[getCabietPosition()];
    }

    public String getRowNO() {
        String rowNO = rowList.get(getRowPosition());
        return rowNO;
    }

    public List<String> getColumnNOList() {
        List<String> columnNOList = new ArrayList<>();
        if (getColumnPosition() == 0) {
            //所有
            for (int i = 1; i < columnList.size(); i++) {
                columnNOList.add(columnList.get(i));
            }
        } else {
            columnNOList.add(columnList.get(getColumnPosition()));
        }
        return columnNOList;
    }

    /**
     * 货道编号
     *
     * @return
     */
    public List<TestResultBean> getTestTuneNOList() {
        List<TestResultBean> tuneNOList = new ArrayList<>();
        List<String> columnNOList = getColumnNOList();
        for (int i = 0; i < columnNOList.size(); i++) {
            String tuneNO = getCabitNO() + getRowNO() + columnNOList.get(i);
            tuneNOList.add(new TestResultBean(tuneNO, "等待测试..."));
        }
        return tuneNOList;
    }

    /**
     * 测试出货
     *
     * @param index
     */
    private void testOut(final int index) {

        stopCountTimer();
        if (isContinueExe) {
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            exectorDealy(index);
                        }
                    });
                }
            }, 1000);
        }
    }

    private void exectorDealy(final int index) {

        if (index >= resultList.size()) {
            btnTest.setEnabled(true);
            setHomeButtonEnabled(true);
            return;
        }

        rvResult.smoothScrollToPosition(index);
        btnTest.setEnabled(false);
        setHomeButtonEnabled(false);

        //测试用的出货data
        String dataOutWare = SeriaCmdRequestManager
                .getInstacne().getDataOutWare(resultList.get(index)
                        .getTuneNO(), true);

        LogUtil.i(TAG, "{MachineTestActivity}[exectorDealy]index:" + index + ",电机测试出货数据：" + dataOutWare);
        resultList.get(index).setState("测试中...");
        mRvRestultAdapter.notifyDataSetChanged();

        new SerialClientManager().setCallback(SerialCmdEnum.OUT_WARE, new SerialCallback() {
            @Override
            public void onSuccess(String cmd, String data,String tuneNO, String orderNO) {
                LogUtil.i(TAG, "{MachineTestActivity->SerialCallback}[onSuccess]");
                outWareAnswerSuccess(data, index);
            }

            @Override
            public void onFile(String msg,String tuneNO, String orderNO) {
                LogUtil.i(TAG, "{MachineTestActivity->SerialCallback}[onFile]");
                resultList.get(index).setState("出货响应失败，" + msg);
                mRvRestultAdapter.notifyDataSetChanged();
                testOut(index + 1);
            }
        }).setData(dataOutWare).execute();
    }


    /**
     * 关掉 间隔查询的计时器
     */
    private void stopCountTimer() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }


    /**
     * 出货指令 应答成功（不是出货成功）
     *
     * @param data
     * @param index
     */
    private void outWareAnswerSuccess(String data, int index) {
        String address = data.substring(0, 2);
        String result = data.substring(2);

        LogUtil.i(TAG, "{MachineTestActivity}[outWareAnswerSuccess]result :" + result);
        if (ResultEnum.Success.getValue().equals(result)) {
            //应答成功,查询出货结果
            startCheckTask(index);
            resultList.get(index).setState("正在查询出货结果...");
            mRvRestultAdapter.notifyDataSetChanged();
        } else if (ResultEnum.Fail.getValue().equals(result)) {
            //表示串口流水码重复，说明机器已在处理，同上开始查询任务
            startCheckTask(index);
            resultList.get(index).setState("正在查询出货结果...");
            mRvRestultAdapter.notifyDataSetChanged();
        } else if ("2".equals(result)) {
            ToastUtils.showShort("货道编号错误");
            resultList.get(index).setState("货道编号错误");
            mRvRestultAdapter.notifyDataSetChanged();
            testOut(index + 1);
        } else {
            //应答失败，发送出货指令，驱动板故障
            resultList.get(index).setState("出货失败，机器故障");
            mRvRestultAdapter.notifyDataSetChanged();
            testOut(index + 1);
        }
    }

    @Override
    protected void onStop() {
        isContinueExe = false;
        stopCountTimer();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (serialClientManager != null) {
            serialClientManager.stopTimeOutTask();
        }
    }

    /**
     * 查询出货结果
     *
     * @param index
     */
    private void startCheckTask(final int index) {
        stopCountTimer();

        //延迟200ms执行查询
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        checkTask(index);
                    }
                });
            }
        }, 1000);

    }

    private void checkTask(final int index) {
        final String dataWareResul = SeriaCmdRequestManager.getInstacne()
                .getCheckDataWareResul(resultList.get(index).getTuneNO());

        LogUtil.i(TAG, "{MachineTestActivity}[startCheckTask]：" + dataWareResul);
        countDownTimer = new CountDownTimer(OUTRESULT_WAIT, OUTRESULT_WAIT_INTERVAL) {

            @Override
            public void onTick(long millisUntilFinished) {
                LogUtil.i(TAG, "{MachineTestActivity->CountDownTimer}[onTick]" + millisUntilFinished);
                checkExecute(index, dataWareResul);
            }

            @Override
            public void onFinish() {
                LogUtil.i(TAG, "{MachineTestActivity->CountDownTimer}[onFinish]");
                resultList.get(index).setState("出货查询结束，出货失败");
                mRvRestultAdapter.notifyDataSetChanged();
                testOut(index + 1);
            }
        };

        countDownTimer.start();

        checkExecute(index, dataWareResul);
    }

    private void checkExecute(final int index, String dataWareResul) {
        LogUtil.i(TAG, "{MachineTestActivity}[checkExecute]index:" + index);

        if (serialClientManager != null) {
            serialClientManager.stopTimeOutTask();
            serialClientManager.setCallback(null, null);
        }

        serialClientManager = new SerialClientManager();
        serialClientManager.setCallback(SerialCmdEnum.CHECK_OUT_WARE_RESULT, new SerialCallback() {
            @Override
            public void onSuccess(String cmd, String data,String tuneNO, String orderNO) {
                String address = data.substring(0, 2);
                String result = data.substring(2, 3);
                //红外检测结果
                String state = StringUtil.convertStringToHex(result);
                LogUtil.i(TAG, "{MachineTestActivity->SerialCallback(查询出货)}[onSuccess]index:"
                        + index + ",state:" + state);

                if ("30".equals(state)) {
                    //成功出货
                    resultList.get(index).setState("出货成功");
                    testOut(index + 1);

                } else if (state.startsWith("3")) {
                    //正在出货
                    resultList.get(index).setState("正在出货...");
                } else if (state.startsWith("5")) {
                    //出货失败
                    ToastUtils.showShort("出货失败");
                    resultList.get(index).setState("出货失败");
                    testOut(index + 1);
                }
                mRvRestultAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFile(String msg,String tuneNO, String orderNO) {
                LogUtil.i(TAG, "{MachineTestActivity->SerialCallback(查询出货)}[onFile]");
                resultList.get(index).setState("查询请求超时," + msg);
                mRvRestultAdapter.notifyDataSetChanged();
                testOut(index + 1);
            }
        }).setData(dataWareResul).execute();
    }

}
